﻿ 
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SHFK.B2C.YouZanYun.Network;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Dto.Center;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Req;
using SHKF.B2C.YouZanYun.Model.Inter.Center;
using SHKF.B2C.YouZanYun.Model.Inter.ItemsInventory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SHKF.B2C.YouZanYun.Service.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class ProductController : Base2Controller
    {
        private readonly ProductBaseBLL productBaseBLL;
        private readonly ProductInfoBLL productInfoBLL;
        private readonly ShopBLL shopBLL;
        private readonly ShopMapBLL shopMapBLL;

        public ProductController(
            ProductBaseBLL productBaseBLL,
            ProductInfoBLL productInfoBLL,
            ShopBLL shopBLL,
            ShopMapBLL shopMapBLL, 
           IServiceProvider serviceProvider,
           ILogger<ProductController> logger) : base(serviceProvider, logger)
        {
            this.productBaseBLL = productBaseBLL;
            this.productInfoBLL = productInfoBLL;
            this.shopBLL = shopBLL;
            this.shopMapBLL = shopMapBLL;
        }

        [HttpGet("items/inventory")]
        public async Task<ItemsInventoryResult> ItemsInventory(long node_kdt_id, string q)
        {
            ItemsInventoryParam param = new ItemsInventoryParam();
            param.node_kdt_id = node_kdt_id;
            param.q = q;
            string authority_id = param.node_kdt_id.ToString();

            await base.GetToken(authority_id);

            ItemsInventoryResult dto = await this.httpClient.ItemsInventoryGet(authority_id, param);

            return dto;
        }

        [HttpGet("OnSale")]
        public async Task<ItemsDto> OnSale(string authority_id)
        { 
            await base.GetToken(authority_id); 
            ItemsDto dto = await this.httpClient.GetOnSaleProduct(authority_id, null);

            return dto;
        }

        [HttpGet("ItemSearch")]
        public async Task<ItemsDto> ItemSearch(string authority_id, string key)
        {
            await base.GetToken(authority_id);
            ItemsDto dto = await this.httpClient.ItemSearch(authority_id, key); 
            return dto;
        }

        [HttpPost("Import")]
        public async Task<DataDto> Import(ProductInfo data)
        {
            DataDto dto = new DataDto();

            try
            {
                int CompanySN = data.CompanySN;

                #region 保存商品库

                ProductBaseEntity productBase = data;

                //如果已经存在则用商品库的信息
                ProductBaseEntity oldInfo = this.productBaseBLL.Get(data.Upc);
                if (oldInfo != null)
                {
                    productBase.ProductName = oldInfo.ProductName;
                    productBase.Upc = oldInfo.Upc;
                    productBase.LiceseId = oldInfo.LiceseId;
                    productBase.Spec = oldInfo.Spec;
                    productBase.Price = oldInfo.Price;
                    productBase.Made = oldInfo.Made;
                    productBase.Unit = oldInfo.Unit;
                    productBase.Model = oldInfo.Model;
                    productBase.Manufacturer = oldInfo.Manufacturer;

                    productBase.Validate = oldInfo.Validate;
                    productBase.CommonTitle = oldInfo.CommonTitle;
                    productBase.ConditionOfStorage = oldInfo.ConditionOfStorage; ;
                    productBase.Prescript = oldInfo.Prescript;

                    productBase.Brand = oldInfo.Brand;
                    productBase.Functions = oldInfo.Functions;
                    productBase.Ingredients = oldInfo.Ingredients;
                    productBase.UsageDosage = oldInfo.UsageDosage;
                    productBase.Taboo = oldInfo.Taboo;
                    productBase.Packing = oldInfo.Packing;
                    productBase.SN = oldInfo.SN;
                }
                else
                {
                    productBase = this.productBaseBLL.Save(productBase);
                }
  
                #endregion

                #region 保存总部ID,保存映射表

                //保存总部产品信息
                ProductInfoEntity productInfo0 = new ProductInfoEntity();
                productInfo0.ShopSN = 0;
                productInfo0.CompanySN = CompanySN;
                productInfo0.ID = data.ID;
                productInfo0.FKSN = productBase.SN;
                this.productInfoBLL.Save(productInfo0);

                string strPoiCode = this.shopMapBLL.GetKdtId(CompanySN).ToString();
                 await base.GetToken(strPoiCode);
                ItemsDto dto0 = await this.httpClient.ItemSearch(strPoiCode, data.ID);
                if(dto0.success)
                { 
                    ProductInfoMapEntity map = new ProductInfoMapEntity();
                    map.FKSN = productInfo0.SN;
                    map.Upc = data.Upc;
                    map.Platform = PlatformEnum.YouZanYun;
                    map.app_medicine_code = dto0.data.items[0].item_id.ToString(); 
                    this.productInfoBLL.MapSave(map);
                }

                #endregion

                //保存所有分店铺商品 
                List<ShopEntity> shops = this.shopBLL.Query(CompanySN, "");
                shops = shops.FindAll(w=>w.ShopSN > 0);
                foreach (ShopEntity shopEntity in shops)
                {
                    //保存店铺商品
                    ProductInfoEntity productInfo = new ProductInfoEntity();
                    productInfo.ShopSN = shopEntity.ShopSN;
                    productInfo.CompanySN = CompanySN;
                    productInfo.ID = data.ID;
                    productInfo.FKSN = productBase.SN;
                    this.productInfoBLL.Save(productInfo);

                    List<ShopMapEntity> shopMapEntity = this.shopMapBLL.Query(shopEntity.ShopSN, PlatformEnum.YouZanYun);
                    if(shopMapEntity.Count > 0 )
                    { 
                        string app_poi_code = shopMapEntity[0].app_poi_code.ToString();
                        this.httpClient.access_token = "";
                        await base.GetToken(app_poi_code);

                        //获取分店ID
                        ItemsDto dto2 = await this.httpClient.ItemSearch(app_poi_code, productInfo.ID); 
                        if(dto2.success)
                        { 
                            ProductInfoMapEntity map = new ProductInfoMapEntity();
                            map.Platform = PlatformEnum.YouZanYun;
                            map.app_medicine_code = dto2.data.items[0].item_id.ToString();
                            map.Upc = productBase.Upc;
                            map.FKSN = productInfo.SN;

                            //保存映射表
                            this.productInfoBLL.MapSave(map);
                        } 
                    } 
                    else
                    {
                        this.logger.LogInformation($"Product/Import ShopSN:{shopEntity.ShopSN}没有配置有赞云店铺SN");
                    }
                }
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }
    }
}
